<template>
  <div class="user-manage">
    <div class="operation-bar">
      <el-button type="primary" @click="handleAdd">新增用户</el-button>
      <FilterBar
        :status="status"
        :searchQuery="searchQuery"
        showStatus
        showSearch
        :isUser="true"
        @update:status="status = $event"
        @update:searchQuery="searchQuery = $event"
      />
    </div>
    
    <LoadingWrapper :loading="loading">
      <div>
        <el-table 
          v-if="filteredUsers.length > 0"
          :data="paginatedUsers" 
          style="width: 100%" 
          :cell-style="{ padding: '12px 0' }"
        >
          <el-table-column 
            label="序号" 
            width="80"
            align="center"
          >
            <template #default="scope">
              {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column 
            prop="id" 
            label="ID" 
            width="80"
            align="center"
            v-if="false"  
          />
          <el-table-column 
            prop="username" 
            label="用户名" 
            min-width="120"
            align="center"
            show-overflow-tooltip
          />
          <el-table-column 
            prop="postCount" 
            label="发布书籍数" 
            width="100" 
            align="center"
          >
            <template #default="scope">
              <el-button type="text" @click="showUserPosts(scope.row)">
                {{ scope.row.postCount }}
              </el-button>
            </template>
          </el-table-column>
          <el-table-column 
            prop="createTime" 
            label="注册时间" 
            min-width="150"
            align="center"
            show-overflow-tooltip
          >
            <template #default="scope">
              {{ formatDateTime(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column 
            prop="status" 
            label="状态" 
            width="120" 
            align="center"
            :label-class-name="'status-column-header'"
          >
            <template #default="scope">
              <div style="padding-right: 40px">
                <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                  {{ scope.row.status === 1 ? '正常' : '已冻结' }}
                </el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" align="center" fixed="right">
            <template #default="scope">
              <el-tooltip 
                content="编辑" 
                placement="top" 
                :show-after="0"
                :hide-after="0"
              >
                <el-button 
                  type="primary" 
                  link 
                  @click="handleEdit(scope.row)"
                >
                  <el-icon><Edit /></el-icon>
                </el-button>
              </el-tooltip>

              <el-tooltip 
                :content="scope.row.status === 1 ? '冻结' : '解冻'" 
                placement="top"
                :show-after="0"
                :hide-after="0"
              >
                <el-button 
                  :type="scope.row.status === 1 ? 'warning' : 'success'" 
                  link 
                  @click="handleFreezeUser(scope.row)"
                >
                  <el-icon>
                    <component :is="scope.row.status === 1 ? Unlock : Lock" />
                  </el-icon>
                </el-button>
              </el-tooltip>

              <el-tooltip 
                content="删除" 
                placement="top"
                :show-after="0"
                :hide-after="0"
              >
                <el-button 
                  type="danger" 
                  link 
                  @click="handleDelete(scope.row)"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <el-empty v-else description="暂无数据" />
      </div>
    </LoadingWrapper>

    <div class="pagination-wrapper">
      <PaginationBar
        v-if="filteredUsers.length > 0"
        v-model:currentPage="currentPage"
        v-model:pageSize="pageSize"
        :total="filteredUsers.length"
        :pageSizes="[10, 15, 20, 25]"
        @pagination-change="handlePaginationChange"
      />
    </div>

    <!-- 修改编辑/新增对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogType === 'add' ? '新增用户' : '编辑用户'"
      :before-close="handleDialogClose"
      :close-on-click-modal="false"
      width="500px"
      destroy-on-close
    >
      <el-form :model="userForm" ref="userFormRef" :rules="formRules" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input 
            v-model="userForm.username" 
            :placeholder="dialogType === 'edit' ? '' : '请输入用户名'"
          />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogType === 'add'">
          <el-input 
            v-model="userForm.password" 
            type="password" 
            show-password 
            placeholder="请输入密码"
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword" v-if="dialogType === 'add'">
          <el-input 
            v-model="userForm.confirmPassword" 
            type="password" 
            show-password 
            placeholder="请再次输入密码"
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword" v-if="dialogType === 'edit'">
          <el-input 
            v-model="userForm.newPassword" 
            type="password" 
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="handleSave">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 用户发布的书籍列表对话框 -->
    <el-dialog 
      v-model="userPostsDialogVisible" 
      title="用户发布的书籍" 
      width="1200px"
      :close-on-click-modal="false"
      class="user-posts-dialog"
    >
      <div class="dialog-content">
        <el-table 
          :data="paginatedPosts" 
          style="width: 100%"
          :height="600"
        >
          <el-table-column prop="index" label="序号" width="60" align="center" />
          <el-table-column prop="title" label="书名" min-width="180" align="center" />
          <el-table-column prop="author" label="作者" width="120" align="center" />
          <el-table-column 
            prop="intro" 
            label="读后感" 
            min-width="250" 
            align="center" 
            class-name="intro-column"
          />
          <el-table-column label="发布时间" align="center" width="180">
            <template #default="scope">
              <span class="time-text">{{ formatDateTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="综合评分" width="80" align="center">
            <template #default="scope">
              {{ Math.round(scope.row.avgRating) }}
            </template>
          </el-table-column>
          <el-table-column prop="likeCount" label="点赞数" width="80" align="center" />
          <el-table-column prop="commentCount" label="评论数" width="80" align="center" />
          <template #empty>
            <el-empty description="暂无发布的书籍" />
          </template>
        </el-table>
        <div class="dialog-pagination">
          <div class="pagination-actions">
            <el-button 
              :disabled="currentPostPage === 1"
              @click="handlePrevPage"
            >
              <el-icon><ArrowLeft /></el-icon>
            </el-button>
            <span class="page-info">{{ currentPostPage }} / {{ totalPostPages }}</span>
            <el-button 
              :disabled="currentPostPage >= totalPostPages"
              @click="handleNextPage"
            >
              <el-icon><ArrowRight /></el-icon>
            </el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatDateTime } from '@/utils/format'
import { 
  addUser, 
  getUserList, 
  deleteUser, 
  updateUserStatus, 
  updateUser,
  getUserPosts  
} from '@/api/admin'
import { 
  Edit,  // 编辑图标
  Delete,  // 删除图标
  Lock,  // 冻结图标
  Unlock,  // 解冻图标
  ArrowLeft,
  ArrowRight
} from '@element-plus/icons-vue'
import FilterBar from '@/components/filter/FilterBar.vue'
import PaginationBar from '@/components/pagination/PaginationBar.vue'
import LoadingWrapper from '@/components/loading/LoadingWrapper.vue'

const userList = ref([]) // 当前显示的用户数据
const status = ref('1') // '1'表示全部，'2'表示正常，'0'表示已冻结
const searchQuery = ref('')

// 添加 loading 状态
const loading = ref(true)

// 加载用户列表
const loadUserList = async () => {
  try {
    loading.value = true
    const res = await getUserList()
    if (res.code === 200) {
      userList.value = res.data.map((user, index) => ({
        ...user,
        index: index + 1,
        createTime: user.created_at,
        postCount: user.post_count || 0
      }))
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 用户发布的书籍列表 - 初始化为数组
const userPosts = ref([])
const userPostsDialogVisible = ref(false)

const dialogVisible = ref(false)
const dialogType = ref('add')
const userForm = ref({
  id: null,
  username: '',
  password: '',
  confirmPassword: '',
  newPassword: ''
})

// 添加表单引用
const userFormRef = ref(null)

// 添加一个计算属性来动态生成验证规则
const formRules = computed(() => ({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 10, message: '用户名长度在 3 到 10 个字符', trigger: 'blur' },
    { 
      pattern: /^[a-zA-Z0-9]+$/, 
      message: '用户名只能包含字母和数字', 
      trigger: 'blur' 
    }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 10, message: '密码长度在 6 到 10 个字符', trigger: 'blur' },
    { 
      pattern: /^[a-zA-Z0-9]+$/, 
      message: '密码只能包含字母和数字', 
      trigger: 'blur' 
    }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value !== userForm.value.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  newPassword: [
    { min: 6, max: 10, message: '密码长度在 6 到 10 个字符', trigger: 'blur' },
    { 
      pattern: /^[a-zA-Z0-9]+$/, 
      message: '密码只能包含字母和数字', 
      trigger: 'blur' 
    }
  ]
}))

// 添加分页相关变量
const currentPostPage = ref(1)
const postPageSize = ref(10)
const totalPostPages = computed(() => 
  Math.ceil(userPosts.value.length / postPageSize.value)
)

// 分页后的帖子列表
const paginatedPosts = computed(() => {
  const start = (currentPostPage.value - 1) * postPageSize.value
  const end = start + postPageSize.value
  return userPosts.value.slice(start, end)
})

// 上一页
const handlePrevPage = () => {
  if (currentPostPage.value > 1) {
    currentPostPage.value--
  }
}

// 下一页
const handleNextPage = () => {
  if (currentPostPage.value < totalPostPages.value) {
    currentPostPage.value++
  }
}

// 过滤用户列表
const filteredUsers = computed(() => {
  return userList.value.filter(user => {
    // 状态筛选逻辑
    const matchStatus = status.value === '1' || 
      (status.value === '2' && user.status === 1) || 
      (status.value === '0' && user.status === 0)
    
    // 用户名搜索匹配
    const matchQuery = !searchQuery.value || 
      user.username.toLowerCase().includes(searchQuery.value.toLowerCase())
    
    return matchStatus && matchQuery
  })
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)

// 分页后的用户列表
const paginatedUsers = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredUsers.value.slice(start, end)
})

// 处理分页变化
const handlePaginationChange = ({ type, value }) => {
  if (type === 'page') {
    currentPage.value = value
  } else if (type === 'size') {
    pageSize.value = value
    currentPage.value = 1
  }
}

// 监听筛选条件变化，重置页码
watch([searchQuery, status], () => {
  currentPage.value = 1
})

// 显示用户发布的书籍
const showUserPosts = async (user) => {
  try {
    const res = await getUserPosts(user.id)
    if (res.code === 200) {
      userPosts.value = res.data.map((post, index) => ({
        ...post,
        index: index + 1,
        createTime: post.created_at,
        likeCount: post.like_count,
        commentCount: post.comment_count,
        intro: post.thoughts,
        avgRating: post.avg_rating || 0
      }))
      currentPostPage.value = 1  // 重置页码
      userPostsDialogVisible.value = true
    }
  } catch (error) {
    console.error('获取用户发布书籍失败:', error)
    ElMessage.error('获取用户发布书籍失败')
  }
}

// 修改对话框关闭处理
const handleDialogClose = () => {
  if (userForm.value.username || userForm.value.password) {
    ElMessageBox.confirm(
      '确认关闭？未保存的内容将会丢失',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
      .then(() => {
        dialogVisible.value = false
        userForm.value = { id: null, username: '', password: '', confirmPassword: '', newPassword: '' }
        if (userFormRef.value) {
          userFormRef.value.resetFields()
        }
      })
      .catch(() => {
        // 用户取消关闭
      })
  } else {
    dialogVisible.value = false
    userForm.value = { id: null, username: '', password: '', confirmPassword: '', newPassword: '' }
    if (userFormRef.value) {
      userFormRef.value.resetFields()
    }
  }
}

// 修改新增用户处理
const handleAdd = () => {
  dialogType.value = 'add'
  userForm.value = { 
    id: null, 
    username: '', 
    password: '', 
    confirmPassword: '', 
    newPassword: '' 
  }
  if (userFormRef.value) {
    userFormRef.value.resetFields()
  }
  dialogVisible.value = true
}

// 修改编辑用户处理
const handleEdit = (row) => {
  dialogType.value = 'edit'
  userForm.value = {
    id: row.id,
    username: row.username,
    password: '',
    confirmPassword: '',
    newPassword: ''
  }
  dialogVisible.value = true
}

// 删除用户
const handleDelete = async (row) => {
  try {
    await deleteUser(row.id)
    ElMessage.success('删除成功')
    loadUserList()
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error('删除失败')
  }
}

// 冻结/解冻用户
const handleFreezeUser = async (row) => {
  const action = row.status === 1 ? '冻结' : '解冻'
  try {
    await updateUserStatus(row.id, row.status === 1 ? 0 : 1)
    ElMessage.success(`${action}成功`)
    loadUserList()
  } catch (error) {
    console.error(`${action}失败:`, error)
    ElMessage.error(`${action}失败`)
  }
}

// 修改保存处理
const handleSave = async () => {
  if (!userFormRef.value) return
  
  try {
    await userFormRef.value.validate()
    
    if (dialogType.value === 'add') {
      const response = await addUser({
        username: userForm.value.username,
        password: userForm.value.password,
        nickname: userForm.value.username
      })
      if (response.code === 200) {
        ElMessage.success('添加成功')
        dialogVisible.value = false
        // 重置表单
        userForm.value = { id: null, username: '', password: '', confirmPassword: '', newPassword: '' }
        if (userFormRef.value) {
          userFormRef.value.resetFields()
        }
        // 重新加载用户列表
        loadUserList()
      } else {
        ElMessage.error(response.message)
      }
    } else {
      const updateData = {
        username: userForm.value.username
      }
      if (userForm.value.newPassword) {
        updateData.password = userForm.value.newPassword
      }
      const response = await updateUser(userForm.value.id, updateData)
      if (response.code === 200) {
        ElMessage.success('更新成功')
        dialogVisible.value = false
        // 重置表单
        userForm.value = { id: null, username: '', password: '', confirmPassword: '', newPassword: '' }
        if (userFormRef.value) {
          userFormRef.value.resetFields()
        }
        // 重新加载用户列表
        loadUserList()
      } else {
        ElMessage.error(response.message)
      }
    }
  } catch (error) {
    if (error.response?.data) {
      ElMessage.error(error.response.data.message || '操作失败')
    } else {
      ElMessage.error(error.message || '操作失败')
    }
  }
}

// 在组件挂载时获取数据
onMounted(() => {
  loadUserList();
});
</script>

<style scoped>
.user-manage {
  padding: 20px;
}
.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

/* 覆盖 FilterBar 组件的默认下边距 */
:deep(.filter-bar) {
  margin-bottom: 0;  
}

.user-posts-dialog {
  :deep(.el-dialog) {
    height: 650px;
    position: fixed;
    top: 50% !important;
    left: 50% !important;
    transform: translate(-50%, -50%);
    margin: 0 !important;
    max-height: 85vh;
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }
  
  :deep(.el-dialog__body) {
    height: calc(100% - 54px - 52px);
    display: flex;
    flex-direction: column;
    padding: 20px;
    overflow: hidden;
    margin: 0;
  }

  :deep(.el-dialog__header) {
    margin: 0;
    padding: 15px 20px;
  }

  :deep(.el-dialog__footer) {
    margin: 0;
    padding: 10px 20px;
    border-top: 1px solid #ebeef5;
  }

  :deep(.el-table) {
    height: 100%;
    .el-table__body-wrapper {
      overflow-y: auto;
    }
  }
}

.dialog-content {
  flex: 1;
  overflow-y: auto;
  position: relative;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.time-text {
  font-size: 14px;
  color: #606266;
}

.user-posts-dialog {
  :deep(.el-table) {
    .el-table__header th {
      background-color: #f5f7fa;
      padding: 8px 0;
      font-weight: 500;
    }

    .el-table__cell {
      padding: 16px 0;
    }
  }
}

/* 调整按钮和图标大小 */
.el-button {
  padding: 8px 12px;
}

.el-icon {
  font-size: 18px;
}

/* 调整按钮间距 */
.el-table .cell {
  .el-button + .el-button {
    margin-left: 12px;
  }
}

/* 添加读后感列的文字溢出样式 */
:deep(.intro-column .cell) {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 使用深度选择器来修改表头样式 */
:deep(.status-column-header) {
  padding-right: 40px !important;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.pagination-wrapper :deep(.el-pagination) {
  display: flex;
  justify-content: flex-end;
}

.dialog-pagination {
  display: flex;
  justify-content: flex-end;
  padding: 16px 0;
}

.pagination-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.page-info {
  font-size: 14px;
  color: #606266;
  min-width: 50px;
  text-align: center;
}
</style>